package app.service

import org.jooq.impl.DSL
import org.jooq.tools.json.JSONArray
import org.jooq.tools.json.JSONObject
import java.sql.SQLException

class UserService : CommonService() {
    val table = dslTable("user")

    /**
     * 获取用户列表
     * @return JSONArray
     */
    fun getList(): JSONArray? {
        val list = JSONArray()
        var condition = DSL.trueCondition()
        condition = condition.and(DSL.field("is_del").eq(0))
        val fetch = create.select().from(table).where(condition).orderBy(DSL.field("uid").asc()).limit(10).toList()
        if (fetch.isEmpty()) {
            return list
        }
        fetch.forEachIndexed { index, record ->
            val jsonObject = JSONObject()
            jsonObject.put("uid", record.get("uid"))
            jsonObject.put("phone", record.get("phone"))
            jsonObject.put("nickname", record.get("nickname"))
            list.add(index, jsonObject)
        }
        return list
    }

    /**
     * 获取用户信息
     * @param id 用户ID
     * @return JSONObject
     */
    fun getUser(id: Int): JSONObject? {
        val jsonObject = JSONObject()
        var condition = DSL.trueCondition()
        condition = condition.and(DSL.field("uid").eq(id))
        val fetch = create.select().from(table).where(condition).fetchOne()
        if (fetch === null) {
            this.error = "未获取到用户信息"
            return null
        }
        jsonObject.put("uid", fetch.get("uid"))
        jsonObject.put("phone", fetch.get("phone"))
        jsonObject.put("nickname", fetch.get("nickname"))
        return jsonObject
    }

    /**
     * 创建新用户
     * @param user 用户信息
     * @return int
     */
    fun create(user: JSONObject): Any {
        val openid = if (user.getValue("openid") == null) "" else user.getValue("openid")
        try {
            create.insertInto(table)
                .set(DSL.field("phone"), user.getValue("phone"))
                .set(DSL.field("openid"), openid)
                .execute()
            val id = last_insert_id()
            return id
        } catch (e: SQLException) {
            return false
        }
    }

    /**
     * 更新用户
     * @param id 用户ID
     * @param data 用户信息
     * @return boolean
     */
    fun update(id: Int, data: JSONObject): Boolean {
        val record = create.update(table)
                .set(DSL.field("nickname"), data.getValue("nickname"))
                .where(DSL.field("uid").eq(id))
                .execute()
        if (record == 0) return false
        return true
    }

    /**
     * 删除用户
     * @param id 用户ID
     * @return boolean
     */
    fun delete(id: Int): Boolean {
        return dslDelete("user", id)
    }
}